<?php

namespace app\common\service;

use think\facade\Log;

/**
 * 环境配置服务类
 * 根据ThinkPHP的setEnvName方式加载相应的配置文件
 */
class EnvConfigService
{
    /**
     * 支持的环境类型
     */
    const SUPPORTED_ENVIRONMENTS = ['local', 'test', 'prod'];

    /**
     * 默认环境
     */
    const DEFAULT_ENVIRONMENT = 'local';

    /**
     * 当前环境
     * @var string
     */
    protected static string $currentEnvironment = '';

    /**
     * 初始化环境配置
     * @return void
     */
    public static function init(): void
    {
        // 获取当前环境
        $environment = self::getCurrentEnvironment();

        // 记录环境信息
        self::logEnvironmentInfo($environment);
    }

    /**
     * 获取当前环境
     * @return string
     */
    public static function getCurrentEnvironment(): string
    {
        if (empty(self::$currentEnvironment)) {
            // 优先从ThinkPHP应用实例获取环境
            $app = app();
            if (method_exists($app, 'getEnvName')) {
                $env = $app->getEnvName();
            } else {
                $env = '';
            }
           
            // 如果应用实例没有设置环境，尝试从环境变量获取
            if (empty($env)) {
                $env = env('APP_ENV', '');
            }
           
            // 如果环境变量为空，尝试从服务器变量获取
            if (empty($env)) {
                $env = $_SERVER['APP_ENV'] ?? '';
            }

            // 如果还是为空，尝试从域名判断
            if (empty($env)) {
                $env = self::detectEnvironmentByDomain();
            }

            // 验证环境是否支持
            if (!in_array($env, self::SUPPORTED_ENVIRONMENTS)) {
                $env = self::DEFAULT_ENVIRONMENT;
            }

            self::$currentEnvironment = $env;
        }

        return self::$currentEnvironment;
    }

    /**
     * 根据域名检测环境
     * @return string
     */
    protected static function detectEnvironmentByDomain(): string
    {
        $host = $_SERVER['HTTP_HOST'] ?? '';

        if (empty($host)) {
            return self::DEFAULT_ENVIRONMENT;
        }

        // 生产环境域名
        if (strpos($host, 'www.yuyue.com') !== false || strpos($host, 'yuyue.com') !== false) {
            return 'production';
        }

        // 测试环境域名
        if (strpos($host, 'test.yuyue.com') !== false || strpos($host, 'staging') !== false) {
            return 'test';
        }

        // 本地开发环境
        if (strpos($host, 'localhost') !== false || strpos($host, '127.0.0.1') !== false || strpos($host, '.local') !== false) {
            return 'local';
        }

        return self::DEFAULT_ENVIRONMENT;
    }

    /**
     * 记录环境信息
     * @param string $environment
     * @return void
     */
    protected static function logEnvironmentInfo(string $environment): void
    {
        $info = [
            'environment' => $environment,
            'app_debug' => config('app_debug', false),
            'app_host' => config('app_host', ''),
            'database_host' => config('database.connections.mysql.hostname', ''),
            'redis_host' => config('redis.host', ''),
        ];

        Log::info('Application environment info: ' . json_encode($info, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取环境配置信息
     * @return array
     */
    public static function getEnvironmentInfo(): array
    {
        return [
            'current_environment' => self::getCurrentEnvironment(),
            'supported_environments' => self::SUPPORTED_ENVIRONMENTS,
            'app_debug' => config('app_debug', false),
            'app_host' => config('app_host', ''),
            'database' => [
                'host' => config('database.connections.mysql.hostname', ''),
                'database' => config('database.connections.mysql.database', ''),
                'username' => config('database.connections.mysql.username', ''),
            ],
            'redis' => [
                'host' => config('redis.host', ''),
                'port' => config('redis.port', ''),
                'select' => config('redis.select', ''),
            ],
        ];
    }

    /**
     * 检查是否为生产环境
     * @return bool
     */
    public static function isProduction(): bool
    {
        return self::getCurrentEnvironment() === 'prod';
    }

    /**
     * 检查是否为测试环境
     * @return bool
     */
    public static function isTest(): bool
    {
        return self::getCurrentEnvironment() === 'test';
    }

    /**
     * 检查是否为本地环境
     * @return bool
     */
    public static function isLocal(): bool
    {
        return self::getCurrentEnvironment() === 'local';
    }

    /**
     * 获取环境特定的配置值
     * @param string $key 配置键
     * @param mixed $default 默认值
     * @return mixed
     */
    public static function get(string $key, $default = null)
    {
        return config($key, $default);
    }

    /**
     * 设置环境特定的配置值
     * @param string $key 配置键
     * @param mixed $value 配置值
     * @return void
     */
    public static function set(string $key, $value): void
    {
        config([$key => $value]);
    }
}
